const UserDao = require("../dao/user-dao.js");

const UserService = {
	/*用户登录*/
	login(req,res,next){
		//从请求中获取传递的用户名和密码
		const {username,password} = req.body;
		//const {username,password} = req.query;
		console.log(username);
		//从数据库中查询传过来的信息是否存在，对比是否一致
		UserDao.find({username,password})
			   .then((data)=>{
			   		console.log(data);
			   		if (data.length === 1) {//密码一致
			   			if (data[0].password === password) {
			   				res.json({
				   				res_code:1,
				   				res_error:"",
				   				res_body:{
				   					status:1,
				   					data:{
				   						username
				   					}
				   				}
				   			});	
			   			}else{//密码不一致
			   				res.json({
			   					res_code:1,
			   					res_error:"",
			   					res_body:{
			   						status:0,
			   						data:{}
			   					}
			   				});

			   			}
			   		}else {
			   			res.json({
				   			res_code:0,
				   			res_error:"",
				   			res_body:{
				   				status:0
				   			}
			   			})
			   		}
			   		
			  	})
			   .catch((err)=>{
			   		console.log(err);
			   		res.json({
				   			res_code:0,
				   			res_error:err,
				   			res_body:{}
			   			})
			   })
	},
	/*用户注册*/
	register(req,res,next){
		const {username,password,email} = req.body;
		//请求保存在数据库中
		UserDao.save({username,password,email})
			   .then((data)=>{
			   		console.log(data);
			   		res.json({
		   				res_code:1,
		   				res_error:"",
		   				res_body:{
		   					status:1,
		   					data:{
		   						username:data.username,
		   						password:data.password
		   					}
		   				}
	   				});
			   })
			   .catch((err)=>{
			   		res.json({
				   			res_code:0,
				   			res_error:err,
				   			res_body:{}
			   			})
			   })
	},
	/*用户退出*/
	logout(){}
};
module.exports = UserService;
